using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MyFrame.Single
{
    [DefaultExecutionOrder(-100)]
    public class SingletonMonoGlobal<T> : MonoBehaviour, ISingleton where T : MonoBehaviour
    {
        private static T _instance;
        /// <summary>
        /// 线程锁
        /// </summary>
        private static readonly object _lock = new object();
        /// <summary>
        /// 程序是否正在退出
        /// </summary>
        protected static bool ApplicationIsQuitting { get; private set; }

        static SingletonMonoGlobal()
        {
            ApplicationIsQuitting = false;
        }

        public static T Instance
        {
            get
            {
                if (ApplicationIsQuitting)
                {
                    if (Debug.isDebugBuild)
                    {
                        Debug.LogWarning("[Singleton] " + typeof(T) +
                                                " already destroyed on application quit." +
                                                " Won't create again - returning null.");
                    }

                    // return null;
                    return _instance;
                }

                lock (_lock)
                {
                    if (_instance == null)
                    {
                        // 先在场景中找寻
                        _instance = FindFirstObjectByType<T>();

                        T[] oldInstances = FindObjectsOfType<T>(true);
                        if (oldInstances.Length > 1)
                        {
                            if (Debug.isDebugBuild)
                            {
                                Debug.LogWarning("[Singleton] " + typeof(T).Name + " should never be more than 1 in scene!");
                            }

                            return _instance;
                        }

                        // 场景中找不到就创建新物体挂载
                        if (_instance == null)
                        {
                            GameObject singletonObj = new();
                            _instance = singletonObj.AddComponent<T>();
                            singletonObj.name = "(singleton) " + typeof(T);

                            if (Application.isPlaying)
                            {
                                DontDestroyOnLoad(singletonObj);
                            }

                            return _instance;
                        }
                    }

                    return _instance;
                }
            }
        }

        /// <summary>
        /// 当工程运行结束，在退出时，不允许访问单例
        /// </summary>
        protected virtual void OnApplicationQuit()
        {
            ApplicationIsQuitting = true;
        }
        protected virtual void OnDestroy()
        {
            // ApplicationIsQuitting = true;
        }

    }
}